{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Gradient Descent\n",
    ":label:`sec_gd`\n",
    "\n",
    "In this section we are going to introduce the basic concepts underlying gradient descent. This is brief by necessity. See e.g., :cite:`Boyd.Vandenberghe.2004` for an in-depth introduction to convex optimization. Although the latter is rarely used directly in deep learning, an understanding of gradient descent is key to understanding stochastic gradient descent algorithms. For instance, the optimization problem might diverge due to an overly large learning rate. This phenomenon can already be seen in gradient descent. Likewise, preconditioning is a common technique in gradient descent and carries over to more advanced algorithms. Let us start with a simple special case.\n",
    "\n",
    "## Gradient Descent in One Dimension\n",
    "\n",
    "Gradient descent in one dimension is an excellent example to explain why the gradient descent algorithm may reduce the value of the objective function. Consider some continuously differentiable real-valued function $f: \\mathbb{R} \\rightarrow \\mathbb{R}$. Using a Taylor expansion (:numref:`sec_single_variable_calculus`) we obtain that \n",
    "\n",
    "$$f(x + \\epsilon) = f(x) + \\epsilon f'(x) + \\mathcal{O}(\\epsilon^2).$$\n",
    ":eqlabel:`gd-taylor`\n",
    "\n",
    "That is, in first approximation $f(x+\\epsilon)$ is given by the function value $f(x)$ and the first derivative $f'(x)$ at $x$. It is not unreasonable to assume that for small $\\epsilon$ moving in the direction of the negative gradient will decrease $f$. To keep things simple we pick a fixed step size $\\eta > 0$ and choose $\\epsilon = -\\eta f'(x)$. Plugging this into the Taylor expansion above we get\n",
    "\n",
    "$$f(x - \\eta f'(x)) = f(x) - \\eta f'^2(x) + \\mathcal{O}(\\eta^2 f'^2(x)).$$\n",
    "\n",
    "If the derivative $f'(x) \\neq 0$ does not vanish we make progress since $\\eta f'^2(x)>0$. Moreover, we can always choose $\\eta$ small enough for the higher order terms to become irrelevant. Hence we arrive at\n",
    "\n",
    "$$f(x - \\eta f'(x)) \\lessapprox f(x).$$\n",
    "\n",
    "This means that, if we use\n",
    "\n",
    "$$x \\leftarrow x - \\eta f'(x)$$\n",
    "\n",
    "to iterate $x$, the value of function $f(x)$ might decline. Therefore, in gradient descent we first choose an initial value $x$ and a constant $\\eta > 0$ and then use them to continuously iterate $x$ until the stop condition is reached, for example, when the magnitude of the gradient $|f'(x)|$ is small enough or the number of iterations has reached a certain value.\n",
    "\n",
    "For simplicity we choose the objective function $f(x)=x^2$ to illustrate how to implement gradient descent. Although we know that $x=0$ is the solution to minimize $f(x)$, we still use this simple function to observe how $x$ changes. As always, we begin by importing all required modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Functions.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Function<Float, Float> f = x -> x * x; // Objective Function\n",
    "Function<Float, Float> gradf = x -> 2 * x; // Its Derivative\n",
    "\n",
    "NDManager manager = NDManager.newBaseManager();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we use $x=10$ as the initial value and assume $\\eta=0.2$. Using gradient descent to iterate $x$ for 10 times we can see that, eventually, the value of $x$ approaches the optimal solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public float[] gd(float eta) {\n",
    "    float x = 10f;\n",
    "    float[] results = new float[11];\n",
    "    results[0] = x;\n",
    "    \n",
    "    for (int i = 0; i < 10; i++) {\n",
    "        x -= eta * gradf.apply(x);\n",
    "        results[i + 1] = x;\n",
    "    }\n",
    "    System.out.printf(\"epoch 10, x: %f\\n\", x);\n",
    "    return results;\n",
    "}\n",
    "\n",
    "float[] res = gd(0.2f);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The progress of optimizing over $x$ can be plotted as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/* Saved in GradDescUtils.java */\n",
    "public void plotGD(float[] x, float[] y, float[] segment, Function<Float, Float> func, \n",
    "                                 int width, int height) {\n",
    "    // Function Line\n",
    "    ScatterTrace trace = ScatterTrace.builder(Functions.floatToDoubleArray(x), \n",
    "                                              Functions.floatToDoubleArray(y))\n",
    "        .mode(ScatterTrace.Mode.LINE)\n",
    "        .build();\n",
    "\n",
    "    // GD Line\n",
    "    ScatterTrace trace2 = ScatterTrace.builder(Functions.floatToDoubleArray(segment), \n",
    "                                               Functions.floatToDoubleArray(Functions.callFunc(segment, func)))\n",
    "        .mode(ScatterTrace.Mode.LINE)\n",
    "        .build();\n",
    "    \n",
    "    // GD Points\n",
    "    ScatterTrace trace3 = ScatterTrace.builder(Functions.floatToDoubleArray(segment), \n",
    "                                               Functions.floatToDoubleArray(Functions.callFunc(segment, func)))\n",
    "        .build();\n",
    "\n",
    "    Layout layout = Layout.builder()\n",
    "        .height(height)\n",
    "        .width(width)\n",
    "        .showLegend(false)\n",
    "        .build();\n",
    "    \n",
    "    display(new Figure(layout, trace, trace2, trace3));\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/* Saved in GradDescUtils.java */\n",
    "public void showTrace(float[] res) {\n",
    "    float n = 0;\n",
    "    for (int i = 0; i < res.length; i++) {\n",
    "        if (Math.abs(res[i]) > n) {\n",
    "            n = Math.abs(res[i]);\n",
    "        }\n",
    "    }\n",
    "    NDArray fLineND = manager.arange(-n, n, 0.01f);\n",
    "    float[] fLine = fLineND.toFloatArray();\n",
    "    plotGD(fLine, Functions.callFunc(fLine, f), res, f, 500, 400);\n",
    "}\n",
    "\n",
    "showTrace(res);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Learning Rate\n",
    ":label:`section_gd-learningrate`\n",
    "\n",
    "The learning rate $\\eta$ can be set by the algorithm designer. If we use a learning rate that is too small, it will cause $x$ to update very slowly, requiring more iterations to get a better solution. To show what happens in such a case, consider the progress in the same optimization problem for $\\eta = 0.05$. As we can see, even after 10 steps we are still very far from the optimal solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "showTrace(gd(0.05f));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Conversely, if we use an excessively high learning rate, $\\left|\\eta f'(x)\\right|$ might be too large for the first-order Taylor expansion formula. That is, the term $\\mathcal{O}(\\eta^2 f'^2(x))$ in :eqref:`gd-taylor` might become significant. In this case, we cannot guarantee that the iteration of $x$ will be able to lower the value of $f(x)$. For example, when we set the learning rate to $\\eta=1.1$, $x$ overshoots the optimal solution $x=0$ and gradually diverges."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "showTrace(gd(1.1f));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Local Minima\n",
    "\n",
    "To illustrate what happens for nonconvex functions consider the case of $f(x) = x \\cdot \\cos c x$. This function has infinitely many local minima. Depending on our choice of learning rate and depending on how well conditioned the problem is, we may end up with one of many solutions. The example below illustrates how an (unrealistically) high learning rate will lead to a poor local minimum."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float c = (float)(0.15f * Math.PI);\n",
    "\n",
    "Function<Float, Float> f = x -> x * (float)Math.cos(c * x);\n",
    "\n",
    "Function<Float, Float> gradf = x -> (float)(Math.cos(c * x) - c * x * Math.sin(c * x));\n",
    "\n",
    "showTrace(gd(2));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multivariate Gradient Descent\n",
    "\n",
    "Now that we have a better intuition of the univariate case, let us consider the situation where $\\mathbf{x} \\in \\mathbb{R}^d$. That is, the objective function $f: \\mathbb{R}^d \\to \\mathbb{R}$ maps vectors into scalars. Correspondingly its gradient is multivariate, too. It is a vector consisting of $d$ partial derivatives:\n",
    "\n",
    "$$\\nabla f(\\mathbf{x}) = \\bigg[\\frac{\\partial f(\\mathbf{x})}{\\partial x_1}, \\frac{\\partial f(\\mathbf{x})}{\\partial x_2}, \\ldots, \\frac{\\partial f(\\mathbf{x})}{\\partial x_d}\\bigg]^\\top.$$\n",
    "\n",
    "Each partial derivative element $\\partial f(\\mathbf{x})/\\partial x_i$ in the gradient indicates the rate of change of $f$ at $\\mathbf{x}$ with respect to the input $x_i$. As before in the univariate case we can use the corresponding Taylor approximation for multivariate functions to get some idea of what we should do. In particular, we have that \n",
    "\n",
    "$$f(\\mathbf{x} + \\mathbf{\\epsilon}) = f(\\mathbf{x}) + \\mathbf{\\epsilon}^\\top \\nabla f(\\mathbf{x}) + \\mathcal{O}(\\|\\mathbf{\\epsilon}\\|^2).$$\n",
    ":eqlabel:`gd-multi-taylor`\n",
    "\n",
    "In other words, up to second order terms in $\\mathbf{\\epsilon}$ the direction of steepest descent is given by the negative gradient $-\\nabla f(\\mathbf{x})$. Choosing a suitable learning rate $\\eta > 0$ yields the prototypical gradient descent algorithm:\n",
    "\n",
    "$\\mathbf{x} \\leftarrow \\mathbf{x} - \\eta \\nabla f(\\mathbf{x}).$\n",
    "\n",
    "To see how the algorithm behaves in practice let us construct an objective function $f(\\mathbf{x})=x_1^2+2x_2^2$ with a two-dimensional vector $\\mathbf{x} = [x_1, x_2]^\\top$ as input and a scalar as output. The gradient is given by $\\nabla f(\\mathbf{x}) = [2x_1, 4x_2]^\\top$. We will observe the trajectory of $\\mathbf{x}$ by gradient descent from the initial position $[-5, -2]$. We need two more helper functions. The first uses an update function and applies it $20$ times to the initial value. The second helper visualizes the trajectory of $\\mathbf{x}$.\n",
    "\n",
    "We also create a `Weights` class to make it easier to store the weight parameters and return them in functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "/* Saved in GradDescUtils.java */\n",
    "public class Weights {\n",
    "    public float x1, x2;\n",
    "    public Weights(float x1, float x2) {\n",
    "        this.x1 = x1;\n",
    "        this.x2 = x2;\n",
    "    }\n",
    "}\n",
    "\n",
    "/* Saved in GradDescUtils.java */\n",
    "/* Optimize a 2D objective function with a customized trainer. */\n",
    "public ArrayList<Weights> train2d(Function<Float[], Float[]> trainer, int steps) {\n",
    "    // s1 and s2 are internal state variables and will\n",
    "    // be used later in the chapter\n",
    "    float x1 = -5f, x2 = -2f, s1 = 0f, s2 = 0f;\n",
    "    ArrayList<Weights> results = new ArrayList<>();\n",
    "    results.add(new Weights(x1, x2));\n",
    "    for (int i = 1; i < steps + 1; i++) {\n",
    "        Float[] step = trainer.apply(new Float[]{x1, x2, s1, s2});\n",
    "        x1 = step[0];\n",
    "        x2 = step[1];\n",
    "        s1 = step[2];\n",
    "        s2 = step[3];\n",
    "        results.add(new Weights(x1, x2));\n",
    "        System.out.printf(\"epoch %d, x1 %f, x2 %f\\n\", i, x1, x2);\n",
    "    }\n",
    "    return results;\n",
    "}\n",
    "\n",
    "import java.util.function.BiFunction;\n",
    "\n",
    "/* Saved in GradDescUtils.java */\n",
    "/* Show the trace of 2D variables during optimization. */        \n",
    "public void showTrace2d(BiFunction<Float, Float, Float> f, ArrayList<Weights> results) {\n",
    "    // TODO: add when tablesaw adds support for contour and meshgrids\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we observe the trajectory of the optimization variable $\\mathbf{x}$ for learning rate $\\eta = 0.1$. We can see that after 20 steps the value of $\\mathbf{x}$ approaches its minimum at $[0, 0]$. Progress is fairly well-behaved albeit rather slow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float eta = 0.1f;\n",
    "\n",
    "BiFunction<Float, Float, Float> f = (x1, x2) -> x1 * x1 + 2 * x2 * x2; // Objective\n",
    "\n",
    "BiFunction<Float, Float, Float[]> gradf = (x1, x2) -> new Float[]{2 * x1, 4 * x2}; // Gradient\n",
    "\n",
    "Function<Float[], Float[]> gd = (state) -> {\n",
    "    Float x1 = state[0];\n",
    "    Float x2 = state[1];\n",
    "    \n",
    "    Float[] g = gradf.apply(x1, x2); // Compute Gradient\n",
    "    Float g1 = g[0];\n",
    "    Float g2 = g[1];\n",
    "    \n",
    "    return new Float[]{x1 - eta * g1, x2 - eta * g2, 0f, 0f}; // Update Variables\n",
    "};\n",
    "\n",
    "showTrace2d(f, train2d(gd, 20));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Contour Gradient Descent.](https://d2l-java-resources.s3.amazonaws.com/img/contour_gd.svg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adaptive Methods\n",
    "\n",
    "As we could see in :numref:`section_gd-learningrate`, getting the learning rate $\\eta$ \"just right\" is tricky. If we pick it too small, we make no progress. If we pick it too large, the solution oscillates and in the worst case it might even diverge. What if we could determine $\\eta$ automatically or get rid of having to select a step size at all? Second order methods that look not only at the value and gradient of the objective but also at its *curvature* can help in this case. While these methods cannot be applied to deep learning directly due to the computational cost, they provide useful intuition into how to design advanced optimization algorithms that mimic many of the desirable properties of the algorithms outlined below.\n",
    "\n",
    "\n",
    "### Newton's Method\n",
    "\n",
    "Reviewing the Taylor expansion of $f$ there is no need to stop after the first term. In fact, we can write it as \n",
    "\n",
    "$$f(\\mathbf{x} + \\mathbf{\\epsilon}) = f(\\mathbf{x}) + \\mathbf{\\epsilon}^\\top \\nabla f(\\mathbf{x}) + \\frac{1}{2} \\mathbf{\\epsilon}^\\top \\nabla \\nabla^\\top f(\\mathbf{x}) \\mathbf{\\epsilon} + \\mathcal{O}(\\|\\mathbf{\\epsilon}\\|^3).$$\n",
    ":eqlabel:`gd-hot-taylor`\n",
    "\n",
    "To avoid cumbersome notation we define $H_f := \\nabla \\nabla^\\top f(\\mathbf{x})$ to be the *Hessian* of $f$. This is a $d \\times d$ matrix. For small $d$ and simple problems $H_f$ is easy to compute. For deep networks, on the other hand, $H_f$ may be prohibitively large, due to the cost of storing $\\mathcal{O}(d^2)$ entries. Furthermore it may be too expensive to compute via backprop as we would need to apply backprop to the backpropagation call graph. For now let us ignore such considerations and look at what algorithm we'd get. \n",
    "\n",
    "After all, the minimum of $f$ satisfies $\\nabla f(\\mathbf{x}) = 0$. Taking derivatives of :eqref:`gd-hot-taylor` with regard to $\\mathbf{\\epsilon}$ and ignoring higher order terms we arrive at \n",
    "\n",
    "$$\\nabla f(\\mathbf{x}) + H_f \\mathbf{\\epsilon} = 0 \\text{ and hence } \n",
    "\\mathbf{\\epsilon} = -H_f^{-1} \\nabla f(\\mathbf{x}).$$\n",
    "\n",
    "That is, we need to invert the Hessian $H_f$ as part of the optimization problem.\n",
    "\n",
    "For $f(x) = \\frac{1}{2} x^2$ we have $\\nabla f(x) = x$ and $H_f = 1$. Hence for any $x$ we obtain $\\epsilon = -x$. In other words, a single step is sufficient to converge perfectly without the need for any adjustment! Alas, we got a bit lucky here since the Taylor expansion was exact. Let us see what happens in other problems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float c = 0.5f;\n",
    "\n",
    "Function<Float, Float> f = x -> (float)Math.cosh(c * x); // Objective\n",
    "\n",
    "Function<Float, Float> gradf = x -> c * (float)Math.sinh(c * x); // Derivative\n",
    "\n",
    "Function<Float, Float> hessf = x -> c * c * (float)Math.cosh(c * x); // Hessian\n",
    "\n",
    "// Hide learning rate for now\n",
    "public float[] newton(float eta) {\n",
    "    float x = 10f;\n",
    "    float[] results = new float[11];\n",
    "    results[0] = x;\n",
    "    \n",
    "    for (int i = 0; i < 10; i++) {\n",
    "        x -= eta * gradf.apply(x) / hessf.apply(x);\n",
    "        results[i + 1] = x;\n",
    "    }\n",
    "    System.out.printf(\"epoch 10, x: %f\\n\", x);\n",
    "    return results;\n",
    "}\n",
    "\n",
    "showTrace(newton(1));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let us see what happens when we have a *nonconvex* function, such as $f(x) = x \\cos(c x)$. After all, note that in Newton's method we end up dividing by the Hessian. This means that if the second derivative is *negative* we would walk into the direction of *increasing* $f$. That is a fatal flaw of the algorithm. Let us see what happens in practice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c = 0.15f * (float)Math.PI;\n",
    "\n",
    "Function<Float, Float> f = x -> x * (float)Math.cos(c * x);\n",
    "\n",
    "Function<Float, Float> gradf = x -> (float)(Math.cos(c * x) - c * x * Math.sin(c * x));\n",
    "\n",
    "Function<Float, Float> hessf = x -> (float)(-2 * c * Math.sin(c * x) - \n",
    "                                    x * c * c * Math.cos(c * x));\n",
    "                                    \n",
    "showTrace(newton(1));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This went spectacularly wrong. How can we fix it? One way would be to \"fix\" the Hessian by taking its absolute value instead. Another strategy is to bring back the learning rate. This seems to defeat the purpose, but not quite. Having second order information allows us to be cautious whenever the curvature is large and to take longer steps whenever the objective is flat. Let us see how this works with a slightly smaller learning rate, say $\\eta = 0.5$. As we can see, we have quite an efficient algorithm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "showTrace(newton(0.5f));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Convergence Analysis\n",
    "\n",
    "We only analyze the convergence rate for convex and three times differentiable $f$, where at its minimum $x^*$ the second derivative is nonzero, i.e., where $f''(x^*) > 0$. The multivariate proof is a straightforward extension of the argument below and omitted since it doesn't help us much in terms of intuition. \n",
    "\n",
    "Denote by $x_k$ the value of $x$ at the $k$-th iteration and let $e_k := x_k - x^*$ be the distance from optimality. By Taylor series expansion we have that the condition $f'(x^*) = 0$ can be written as\n",
    "\n",
    "$$0 = f'(x_k - e_k) = f'(x_k) - e_k f''(x_k) + \\frac{1}{2} e_k^2 f'''(\\xi_k).$$\n",
    "\n",
    "This holds for some $\\xi_k \\in [x_k - e_k, x_k]$. Recall that we have the update $x_{k+1} = x_k - f'(x_k) / f''(x_k)$. Dividing the above expansion by $f''(x_k)$ yields\n",
    "\n",
    "$$e_k - f'(x_k) / f''(x_k) = \\frac{1}{2} e_k^2 f'''(\\xi_k) / f''(x_k).$$ \n",
    "\n",
    "Plugging in the update equations leads to the following bound $e_{k+1} \\leq e_k^2 f'''(\\xi_k) / f'(x_k)$. Consequently, whenever we are in a region of bounded $f'''(\\xi_k) / f''(x_k) \\leq c$, we have a quadratically decreasing error $e_{k+1} \\leq c e_k^2$. \n",
    "\n",
    "As an aside, optimization researchers call this *linear* convergence, whereas a condition such as $e_{k+1} \\leq \\alpha e_k$ would be called a *constant* rate of convergence. \n",
    "Note that this analysis comes with a number of caveats: We do not really have much of a guarantee when we will reach the region of rapid convergence. Instead, we only know that once we reach it, convergence will be very quick. Second, this requires that $f$ is well-behaved up to higher order derivatives. It comes down to ensuring that $f$ does not have any \"surprising\" properties in terms of how it might change its values. \n",
    "\n",
    "### Preconditioning\n",
    "\n",
    "Quite unsurprisingly computing and storing the full Hessian is very expensive. It is thus desirable to find alternatives. One way to improve matters is by avoiding to compute the Hessian in its entirety but only compute the *diagonal* entries. While this is not quite as good as the full Newton method, it is still much better than not using it. Moreover, estimates for the main diagonal elements are what drives some of the innovation in stochastic gradient descent optimization algorithms. This leads to update algorithms of the form\n",
    "\n",
    "$$\\mathbf{x} \\leftarrow \\mathbf{x} - \\eta \\mathrm{diag}(H_f)^{-1} \\nabla \\mathbf{x}.$$\n",
    "\n",
    "To see why this might be a good idea consider a situation where one variable denotes height in millimeters and the other one denotes height in kilometers. Assuming that for both the natural scale is in meters we have a terrible mismatch in parameterizations. Using preconditioning removes this. Effectively preconditioning with gradient descent amounts to selecting a different learning rate for each coordinate. \n",
    "\n",
    "### Gradient Descent with Line Search\n",
    "\n",
    "One of the key problems in gradient descent was that we might overshoot the goal or make insufficient progress. A simple fix for the problem is to use line search in conjunction with gradient descent. That is, we use the direction given by $\\nabla f(\\mathbf{x})$ and then perform binary search as to which step length $\\eta$ minimizes $f(\\mathbf{x} - \\eta \\nabla f(\\mathbf{x}))$. \n",
    "\n",
    "This algorithm converges rapidly (for an analysis and proof see e.g., :cite:`Boyd.Vandenberghe.2004`). However, for the purpose of deep learning this is not quite so feasible, since each step of the line search would require us to evaluate the objective function on the entire dataset. This is way too costly to accomplish. \n",
    "\n",
    "## Summary\n",
    "\n",
    "* Learning rates matter. Too large and we diverge, too small and we do not make progress.\n",
    "* Gradient descent can get stuck in local minima.\n",
    "* In high dimensions adjusting learning the learning rate is complicated.\n",
    "* Preconditioning can help with scale adjustment.\n",
    "* Newton's method is a lot faster *once* it has started working properly in convex problems.\n",
    "* Beware of using Newton's method without any adjustments for nonconvex problems. \n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Experiment with different learning rates and objective functions for gradient descent.\n",
    "1. Implement line search to minimize a convex function in the interval $[a, b]$.\n",
    "    * Do you need derivatives for binary search, i.e., to decide whether to pick $[a, (a+b)/2]$ or $[(a+b)/2, b]$. \n",
    "    * How rapid is the rate of convergence for the algorithm?\n",
    "    * Implement the algorithm and apply it to minimizing $\\log (\\exp(x) + \\exp(-2*x -3))$.\n",
    "1. Design an objective function defined on $\\mathbb{R}^2$ where gradient descent is exceedingly slow. Hint - scale different coordinates differently.\n",
    "1. Implement the lightweight version of Newton's method using preconditioning:\n",
    "    * Use diagonal Hessian as preconditioner.\n",
    "    * Use the absolute values of that rather than the actual (possibly signed) values. \n",
    "    * Apply this to the problem above.\n",
    "1. Apply the algorithm above to a number of objective functions (convex or not). What happens if you rotate coordinates by $45$ degrees?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
